package com.xjcs.saplingplan.utils

import android.app.Activity
import android.content.Context
import android.os.Handler
import android.os.Message
import android.text.TextUtils
import android.widget.Toast
import com.alipay.sdk.app.PayTask
import com.tencent.mm.opensdk.modelpay.PayReq
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import com.xjcs.saplingplan.const.toToast

object PaymentUtils {
    private const val SDK_PAY_FLAG = 1
    private const val SDK_AUTH_FLAG = 2

    private var wxApi: IWXAPI? = null
    private var wxAppId: String? = null

    /**
     * 初始化微信支付
     * @param context 上下文
     * @param appId 微信AppId
     */
    fun initWeChatPay(context: Context?, appId: String?) {
        wxAppId = appId
        wxApi = WXAPIFactory.createWXAPI(context, appId)
        wxApi?.registerApp(appId)
    }

    /**
     * 微信支付
     * @param partnerId 商户号
     * @param prepayId 预支付交易会话ID
     * @param nonceStr 随机字符串
     * @param timeStamp 时间戳
     * @param sign 签名
     */
    fun weChatPay(
        partnerId: String?, prepayId: String?, nonceStr: String?,
        timeStamp: String?, sign: String?
    ) {
        if (wxApi == null || !wxApi!!.isWXAppInstalled) {
            "未安装微信或未初始化".toToast()
            return
        }

        val req = PayReq()
        req.appId = wxAppId
        req.partnerId = partnerId
        req.prepayId = prepayId
        req.nonceStr = nonceStr
        req.timeStamp = timeStamp
        req.packageValue = "Sign=WXPay"
        req.sign = sign

        wxApi!!.sendReq(req)
    }

    /**
     * 支付宝支付
     * @param activity 活动上下文
     * @param orderInfo 订单信息
     * @param callback 支付结果回调
     */
    fun aliPay(
        activity: Activity?, orderInfo: String?,
        callback: AliPayCallback
    ) {
        if (TextUtils.isEmpty(orderInfo)) {
            "订单信息不能为空".toToast()
            return
        }

        val handler: Handler = object : Handler() {
            override fun handleMessage(msg: Message) {
                when (msg.what) {
                    SDK_PAY_FLAG -> {
                        val payResult = PayResult(msg.obj as Map<String?, String?>)
                        val resultStatus = payResult.resultStatus
                        // 判断resultStatus 为9000则代表支付成功
                        if (TextUtils.equals(resultStatus, "9000")) {
                            callback.onSuccess()
                        } else {
                            // 其他值就可以判断为支付失败
                            callback.onFailure(resultStatus, payResult.memo)
                        }
                    }

                    else -> {}
                }
            }
        }

        val payRunnable = Runnable {
            val alipay = PayTask(activity)
            val result = alipay.payV2(orderInfo, true)
            val msg = Message()
            msg.what = SDK_PAY_FLAG
            msg.obj = result
            handler.sendMessage(msg)
        }

        val payThread = Thread(payRunnable)
        payThread.start()
    }

    /**
     * 支付宝支付结果
     */
    class PayResult(rawResult: Map<String?, String?>?) {
        var resultStatus: String? = null
        var result: String? = null
        var memo: String? = null

        init {
            if (rawResult != null) {
                for (key in rawResult.keys) {
                    if (TextUtils.equals(key, "resultStatus")) {
                        resultStatus = rawResult[key]
                    } else if (TextUtils.equals(key, "result")) {
                        result = rawResult[key]
                    } else if (TextUtils.equals(key, "memo")) {
                        memo = rawResult[key]
                    }
                }
            }
        }
    }

    /**
     * 支付宝支付回调接口
     */
    interface AliPayCallback {
        fun onSuccess()
        fun onFailure(errorCode: String?, errorMessage: String?)
    }
}